namespace Tycho.Parser.Peg {
    public class OperatorProduction : Production {
        public OperatorProduction () {
            ErrorInformation = new ProductionErrorInformation ("operator");
        }

        public static Terminal CreateTerminal () {
            return new Terminal (new OperatorProduction ());
        }

        protected override ParseResult ReallyParse (char[] source, int startIndex, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            int index = startIndex;
            while (index < source.Length && IsOperator(source[index])) {
                index++;
            }

            if (index > startIndex) {
                var operatorName = new string (source, startIndex, index - startIndex);
                SourceInformation sinfo = parseEnvironment.SourceFileInformation.CreateSourceInformation (startIndex,
                                                                                 index - startIndex);
                var term = new IdentifierTerm (operatorName, sinfo);
                return new ParseResult (index, term, context);
            } else {
                return null;
            }
        }

        private static bool IsOperator (char c) {
            switch (c) {
                case '!':
                case '@':
                case '#':
                case '$':
                case '%':
                case '^':
                case '&':
                case '*':
                case '~':
                case '\\':
                case '|':
                case '<':
                case '>':
                case '.':
                case ':':
                case '/':
                case '?':
                case '-':
                case '+':
                case '=':
                    return true;
                default:
                    return false;
            }
        }
    }
}